package cn.edu.xmist.supermarket.dzh.controller;

import cn.edu.xmist.supermarket.dzh.entity.ProductPO;
import cn.edu.xmist.supermarket.dzh.entity.SupplierPO;
import cn.edu.xmist.supermarket.dzh.service.ProductService;
import cn.edu.xmist.supermarket.dzh.service.SupplierService;
import cn.edu.xmist.supermarket.dzh.util.ObjtoLayJson;
import cn.edu.xmist.supermarket.dzh.config.Vars;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/supplier")
public class SupplierController {

  public static final String[] COLUMNS = {"id", "supplierCode", "supplierName", "supplierBrand"};

  @Autowired private SupplierService supplierService;
  @Autowired private ProductService wareService;

  @RequestMapping("/list")
  public String list(Integer page, Integer limit) throws Exception {
    List<SupplierPO> list = supplierService.list();
    return ObjtoLayJson.ListtoJson(list, COLUMNS);
  }

  @RequestMapping("/saveOrUpdate")
  public String saveOrUpdate(SupplierPO supplier) {
    if (supplier.getId() == null) {
      QueryWrapper<SupplierPO> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("supplier_code", supplier.getSupplierCode());
      List<SupplierPO> list = supplierService.list(queryWrapper);
      if (list.size() > 0) {
        return Vars.FAILURE;
      }
    }
    supplierService.saveOrUpdate(supplier);
    return Vars.SUCCESS;
  }

  @RequestMapping("/deleteById")
  public String deleteById(Long id) {
    SupplierPO supplier = supplierService.getById(id);
    QueryWrapper<ProductPO> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("supplier_code", supplier.getSupplierCode());
    List<ProductPO> list = wareService.list(queryWrapper);
    if (list.size() > 0) {
      return Vars.FAILURE;
    }
    supplierService.removeById(id);
    return Vars.SUCCESS;
  }
}
